
var that
var app = getApp(); 
var Data = require("../../utils/data.js");
var Show = require("../../utils/alert/alert.js"); 
Page({
  data: {
    imgUrls: [],
    more_s:"展开",
    house:null, 
    h_name:"",
    h_size:"",
    h_desc:"", 
    h_cat_num:"", 
    h_price:"",
    h_vip_price:"",

    h_phone: "",
    h_business_hours: "",
    h_address: "",
    h_room_notes:"",//入住须知，这个没加，样式改动较大？？？？？？？？？
    h_booking_info: "",//预约须知
    h_cancel_booking: "",//取消预约
    h_check_out: "",//提前退房

    star_d: null,
    end_d: null,
    house_id: null,//房间类型id(精品、标准)
    day_type: 0,
    day_msg: [],//
    show_type: 0,//1显示选择离店日期，2显示保存，3请选择合理日期
    nextDate:"",  //点击的下一天
    cor: 0,
    f:'',//从订单界面修改日期返回是会设置为order
    opt:{}, //传到此界面的值
  },
  onLoad: function (options) {
    // console.log(options)
  that=this
  that.setData({ house_id: options.house_id})
  that.set_house_msg();
  if (options.startDate && options.endDate) {
    // var startDate = Data.formatDate(options.startDate,"yyyy-MM-dd");
    // var endDate =  Data.formatDate(options.endDate,"yyyy-MM-dd");
    that.data.startDate = options.startDate;
    that.data.endDate = options.endDate;
  
    that.setData({ startDate: options.startDate, endDate: options.endDate, star_d: new Date(options.startDate), end_d: new Date(options.endDate), f: "order", opt:options})

    // console.log(that.data.startDate + "  " + that.data.endDate)
    // console.log(that.data.star_d + "  " + that.data.end_d)

    that.setData({ show_type: 2 });
    var t = { "currentTarget": { "dataset": {"status":1}}};
    // t.currentTarget.dataset.status=1;
    that.setModalStatus2(t);
   }
    wx.getSystemInfo({  success: function (res) { that.setData({ h: res.windowHeight }); } });

    var date = new Date();
    //获取当前的年月
    var cur_year = date.getFullYear();
    var cur_month = date.getMonth() + 1;
    var cur_day = date.getDate();
    const weeks_ch = ['日', '一', '二', '三', '四', '五', '六'];
    //设置数据
    this.setData({
      org_year: date.getFullYear(),//现在时间的年月日
      org_month: date.getMonth(),
      org_day: cur_day,
      weeks_ch
    })
    this.initData(cur_year, cur_month);
    that.house_date();

    if (options.adv && options.adv=="true") { //从首页点预订进入弹出选日期
      wx.showToast({
        title: '加载中', icon: 'loading', duration: 2000,
      })
      var t = { "currentTarget": { "dataset": { "status": 1 } } };
      that.setModalStatus2(t);
    }
  },
  
  onShow: function () {
    if (app.data.iswarm == 1) {
      app.data.iswarm = 2
      var t = { "currentTarget": { "dataset": { "status": 1 } } };
      that.setModalStatus2(t);
    }
    that.setData({ cor: 0})  //判断后续的日期是否都置灰,1找到第一个灰色2将其后日期置灰
   
  },
  more_show:function(){
    if (this.data.more_s=="展开")
    {
      this.setData({ more_s:"收起"});
    } else {
      this.setData({ more_s:"展开"});}
   
  },
  set_house_msg:function(){
    for (var i = 0; i < app.hotelData.house_type.length; i++) {
      if (app.hotelData.house_type[i].id == that.data.house_id) {
        that.setData({ house: app.hotelData.house_type[i] })
        var img = that.data.house.photo.split(",");
       
        img.shift(); //将第一个移除
        that.setData({ house_id: that.data.house.id, h_size: that.data.house.size, h_desc: that.data.house.desc, h_cat_num: that.data.house.live_num, h_price: that.data.house.price, h_name: that.data.house.name, imgUrls: img, h_vip_price: that.data.house.vip_price, });//设置房间规格
        //设置酒店地址，联系电话，营业时间
        that.setData({ h_phone: app.hotelData.house_notict.phone, h_business_hours: app.hotelData.house_notict.business_hours, h_address: app.hotelData.house_notict.address });
        //设置预约须知，退房等
        that.setData({ h_booking_info: app.hotelData.house_notict.booking_info, h_room_notes: app.hotelData.house_notict.room_notes, h_cancel_booking: app.hotelData.house_notict.cancel_booking, h_check_out: app.hotelData.house_notict.check_out });
        wx.setNavigationBarTitle({
          title: that.data.h_name + "详情"
        })

      }
    }
  },
  setModalStatus2: function (e) {  
  //  console.log(e)
    if (app.data.person_msg_rr.level < 1 && app.data.iswarm == 0) {
      wx.navigateTo({ url: '../member/application_member?f=house_detail&house_id='+that.data.house_id })
      return;
    }//若非会员则提示注册会员
    
    var animation2 = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation2 = animation2
    animation2.translateY(300).step();
    this.setData({
      animationData2: animation2.export()
    })
    this.setData({ showModalStatus2: true });
    setTimeout(function () {
      animation2.translateY(0).step()
      this.setData({ animationData2: animation2 })
      if (e.currentTarget.dataset.status == 0) {
        that.setData({ showModalStatus2: false });
        // console.log(111)
        if (that.data.show_type==1){  //只有起始日期退出时清空日期
          that.house_date()
          that.data.startDate = false;
          that.data.start_d = false;
          that.setData({ cor: 0 });  //重新设置制空问题 
          that.setData({ show_type: 0, day_type: 0 })//day_type从0开始配置每天是否有房
          that.initData(that.data.org_year, that.data.org_month + 1);
        }
      }
    }.bind(this), 200)
  },
  //初始化数据
  initData: function (cur_year, cur_month) {
    // 计算最近三个月的对象
    
    var mObject0 = this.calculateDays(cur_year, cur_month);
    if (cur_month + 1 > 12) {
      cur_year = cur_year + 1;
      cur_month = 1;
    } else {
      cur_month = cur_month + 1;
    }
    var mObject1 = this.calculateDays(cur_year, cur_month);
    if (cur_month + 1 > 12) {//月不能大于12
      cur_year = cur_year + 1;
      cur_month = 1;
    } else {
      cur_month = cur_month + 1; 
    }
    var mObject2 = this.calculateDays(cur_year, cur_month);

    if (cur_month + 1 > 12) {//月不能大于12
      cur_year = cur_year + 1;
      cur_month = 1;
    } else {
      cur_month = cur_month + 1;
    }
    var mObject3 = this.calculateDays(cur_year, cur_month);
    if (cur_month + 1 > 12) {//月不能大于12
      cur_year = cur_year + 1;
      cur_month = 1;
    } else {
      cur_month = cur_month + 1;
    }
    var mObject4 = this.calculateDays(cur_year, cur_month);
    if (cur_month + 1 > 12) {//月不能大于12
      cur_year = cur_year + 1;
      cur_month = 1;
    } else {
      cur_month = cur_month + 1;
    }
    var mObject5 = this.calculateDays(cur_year, cur_month);
    this.setData({
      allDays: [mObject0, mObject1, mObject2, mObject3]
    });
  },
  // =============获取当月有多少天（下个月月初是多少）==========
  getThisMonthDays: function (year, month) {
    return new Date(year, month, 0).getDate();
  },
  // =============获取当月第一周第一天是周几===========
  getFirstDayOfWeek: function (year, month) {
    return new Date(Date.UTC(year, month - 1, 1)).getDay();
  },
  //====================计算当前年月空的几天 =============
  calculateEmptyGrids: function (year, month) {
    const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
    let empytGrids = [];
    if (firstDayOfWeek > 0) {
      for (let i = 0; i < firstDayOfWeek; i++) {
        empytGrids.push(i);
      }
    }
    return empytGrids;
  },
  // =====================计算当前年月有哪些天===========
  /**
   * 根据年月计算当前月的天对象状态返回对象
   * mObject 年月对象
   * year  年
   * month 月
   * hasEmptyGrid  是都有空调
   * empytGrids  空天数字
   * days 所有日对象【】
   */
  calculateDays: function (year, month) {
    // console.log(that.data.cor + "  " + that.data.day_type)
    var mObject = {};//月对象
    mObject["year"] = year;
    mObject["month"] = month;
    //计算当前年月空的几天
    var empytGrids = this.calculateEmptyGrids(year, month);
    if (empytGrids.length > 0) {
      mObject["hasEmptyGrid"] = true;
      mObject["empytGrids"] = empytGrids;
    } else {
      mObject["hasEmptyGrid"] = false;
      mObject["empytGrids"] = [];
    }
    var days = [];
    var thisMonthDays = this.getThisMonthDays(year, month);//这个月有多少天
    //现在的时间
    var cusDate = new Date(this.data.org_year, this.data.org_month, this.data.org_day);
    var startDate;
    var endDate;
    if (this.data.startDate && this.data.endDate) {
      startDate = Data.stringToDate(this.data.startDate);
      endDate = Data.stringToDate(this.data.endDate);
      that.setData({ cor: 0})
    }
    if (this.data.startDate) {
      startDate = Data.stringToDate(this.data.startDate);
    }
    for (let i = 1; i <= thisMonthDays; i++) {
      var day = {};
      //加入的时间
      var date = new Date(year, month - 1, i);
      //status 0-不可选择 1-当前时间 2-可选择 3-被选中
      day["day"] = i;

      //比现在的时间比较是大于还是小于，小于则不可点击
      var time = parseInt(Data.calculateTime(date, cusDate));
    
      if (time < 0) {
        day["status"] = 0;  //小于当天的不可点
      } else if (time == 0) {
        day["day_type"] = that.data.day_type
        day["status"] = 1;  //今天
      } else {
        // that.setData({ day_type: that.data.day_type+1});
        that.data.day_type = that.data.day_type + 1
        day["day_type"] = that.data.day_type
        day["status"] = 2;  //大于今天
      }
      //周末day_msg[item.day_type],可入住,大于今天,且周
      // if (that.data.day_msg == [] ){  
      //   if (time >= 0 && (date.getDay() == 0 || date.getDay() == 6)) { day["status"] = 11; }
      // }else{
      //   if (that.data.day_msg[that.data.day_type] == 0 && time >= 0 && (date.getDay() == 0 || date.getDay() == 6)) {
      //     day["status"] = 11;
      //   }
      // }
     //每次点击都重新请求一次，已经在后台判断好了，不需要前台再将下一个灰色的变亮
      // if (that.data.cor == 2) { //将后续的都设为不可点
      //   day["status"] = 0;
      //   day["day_type"] = 1;
      //   } 
      // if (that.data.cor == 1) {
      //     if (that.data.day_msg[that.data.day_type] == 1) {
      //       day["day_type"] = that.data.day_type - 1
      //       day["status"] = 2  //statue,0不可点，1今天可点，2大于今天可点
      //       that.data.cor=2
      //     }
      // } 
      //设置入住离店样式
      if (that.data.cor != 2){
          if (this.data.startDate && this.data.endDate) {
            var stime = parseInt(Data.calculateTime(date, startDate));
            var etime = parseInt(Data.calculateTime(date, endDate));
            if (stime > 0 && etime < 0) {
              day["status"] = 3;  
            }
            if (stime == 0) { day["status"] = 31; that.data.cor = 1 }  //入住
            if (etime == 0) { day["status"] = 32;}   //离店
          } else if (this.data.startDate) {
            var stime = parseInt(Data.calculateTime(date, startDate));
            if (stime == 0) {
              day["status"] = 31;
              that.data.cor = 1 
            }
          } 
      }
      //点击后将其后一天设为可点
      // var nn = this.data.nextDate.split("-")
      // if (nn[0] == year &&nn[1] == month && nn[2] == day['day']) { 
      //   if (that.data.day_msg[that.data.day_type] == 1) { 
      //       day["day_type"] = that.data.day_type - 1
      //       }
      //  day["status"] = 2  //statue,0不可点，1今天可点，2大于今天可点
      // }
    
      days.push(day);
    }
    mObject["days"] = days;
    return mObject;
  },
  // 选择时间
  selectAction: function (e) { 
   
    that.data.day_type = 0;
    if (e.currentTarget.dataset.sta == 1 || e.currentTarget.dataset.ida==0) {   //灰色的不能点
      Show.alertShow(that, "info", "请选择合理时间！"); return; }
    var year = e.currentTarget.dataset.object.year;
    var month = e.currentTarget.dataset.object.month;
    var day = e.currentTarget.dataset.idx + 1;
    var selectDate = new Date(year, month - 1, day);
    var next_Date = new Date(year, month - 1, day+1); //被选择的下一天
    // console.log(next_Date)
    //现在的时间
    var cusDate = new Date(this.data.org_year, this.data.org_month, this.data.org_day);
    var time = parseInt(Data.calculateTime(selectDate, cusDate));
    // console.log(time);//总共居住天数
    if (time < 0) {    //今天之前的日期不能点    
      // app.toast_up("请选择合理时间");
      Show.alertShow(that, "info", "请选择合理时间！");
      return;
    }
    if (this.data.startDate && this.data.endDate) {
       that.house_enddate(selectDate)//查看从哪天置灰
      if (e.currentTarget.dataset.sta == 1 ) {  //重新选择日期时灰色的不能点
        // app.toast_up("请选择合理时间");
        Show.alertShow(that, "info", "请选择合理时间！");
        return;
      }
      that.data.cor = 0; //重新设置制空问题
      //设置入住时间,提醒选择离店日期
      this.setData({ star_d: selectDate, show_type: 1 });
      this.data.startDate = Data.formatDate(selectDate, "yyyy-MM-dd");
      this.data.nextDate = Data.formatDate(next_Date, "yyyy-MM-dd");
      this.data.endDate = null;
    } else if (this.data.startDate) {
      var d = parseInt(Data.calculateTime(selectDate, this.data.star_d));
      if(d<=0){
        that.data.cor = 0; //重新设置制空问题
        that.house_enddate(selectDate)//查看从哪天置灰
        this.setData({ star_d: selectDate, show_type: 1 });//设置入住时间,提醒选择离店日期
        this.data.startDate = Data.formatDate(selectDate, "yyyy-MM-dd");
        this.data.nextDate = Data.formatDate(next_Date, "yyyy-MM-dd");
      }else{
        this.setData({ end_d: selectDate, show_type: 2 }); //设置离店时间,提醒保存
        this.data.endDate = Data.formatDate(selectDate, "yyyy-MM-dd");
        that.save_date();
      }
    } else {
      that.house_enddate(selectDate) //查看从哪天置灰
      if (e.currentTarget.dataset.sta == 1) { //第一次点时灰色不可点
        // app.toast_up("请选择合理时间");
        Show.alertShow(that, "info", "请选择合理时间！");
        return; }
      that.data.cor = 0; //重新设置制空问题
      this.setData({ star_d: selectDate, show_type: 1 }); //设置入住时间,提醒选择离店日期
      this.data.startDate = Data.formatDate(selectDate, "yyyy-MM-dd");
      this.data.nextDate = Data.formatDate(next_Date, "yyyy-MM-dd");
      // console.log(this.data.nextDate)
    }
   
    if (this.data.startDate && this.data.endDate) {
      var sDate = this.data.startDate;
      var eDate = this.data.endDate;
      var d = parseInt(Data.calculateTime(this.data.end_d, this.data.star_d));
      // console.log(d);
      if (d <= 0) {  //开始时间在结束时间后面是错误的
        // app.toast_up("请选择合理时间");
        Show.alertShow(that, "info", "请选择合理时间！");
        that.setData({ show_type: 0 });
        return;
      }
      app.req("get_room_num.html", { 'start_time': sDate, "end_time": eDate, "type": that.data.house_id, "shop_id": wx.getStorageSync('shop_id') },
        function (res){
          // console.log(res)
          if (res.mess <= 0) {
            that.setData({ show_type: 3 });
            Show.alertShow(that, "info", "房已被抢，请刷新日期，选择合理时间！");
            // console.log(that.data.cor + "  " + that.data.day_type)
            return;
          }
        }, function (res) {
          that.selectAction(e)
        });
    } 
    this.initData(this.data.org_year, this.data.org_month + 1);
    //返回选择的时间（有起止时间的时候返回）
  },
  house_date: function () {
    app.req("get_date180.html", { "type": that.data.house_id,"shop_id":wx.getStorageSync('shop_id') },
      function (res) {
        console.log(res)
        that.setData({ day_msg: res.mess });
      }, function (res) {
        // console.log(res);
      });
  },
  house_enddate: function (date) {
    var d = Data.formatDate(date, "yyyy-MM-dd");
    app.req("get_date180_2.html", { 'start_time': d, "type": that.data.house_id,'shop_id':wx.getStorageSync('shop_id') },
      function (res) {
        console.log(res)
        that.setData({ day_msg: res.mess });
      }, function (res) {
        // console.log(res);
      });
  },
  back_order:function(e){
    if (that.data.f == 'order'){
      that.setData({ startDate: that.data.opt.startDate, endDate: that.data.opt.endDate, star_d: new Date(that.data.opt.startDate), end_d: new Date(that.data.opt.endDate), f: "" })
      that.save_date();
    } else { that.setModalStatus2(e)}
   
  },
  save_date: function () {  //点击保存日期，跳转界面
    var sDate = this.data.startDate;
    var eDate = this.data.endDate;
    // console.log(that.data.end_d + "  " + that.data.star_d)
    var d = parseInt(that.calTime(that.data.end_d, that.data.star_d));
    // console.log(d);
    if (d <= 0) {
      // app.toast_up("请选择合理时间");
      Show.alertShow(that, "info", "请选择合理时间！");
      return;
    }
    app.req("get_room_num.html", { 'start_time': sDate, "end_time": eDate, "type": that.data.house_id,"shop_id": wx.getStorageSync('shop_id') },
      function (res) {
        // console.log(res)
        if (res.mess <= 0) {
          that.setData({ show_type: 3});
          Show.alertShow(that, "info", "房已被抢，请刷新日期，选择合理时间！");
          // console.log(that.data.cor + "  " + that.data.day_type)
          return;
        } else {
          that.setData({ showModalStatus2: false });
          wx.redirectTo({
            url: "../my_care/adv_cares?startDate=" + sDate + "&endDate=" + eDate + "&d=" + d + "&house_id=" + that.data.house_id,
          })
        }
      }, function (res) {
        // console.log(res);
      });
  },
  calTime:function(cusDate, oriDate) {
    var cusTime = cusDate.getTime();
    var oriTime = oriDate.getTime();
    return(cusTime - oriTime) / (1000 * 60 * 60 * 24);
},
})